<template>
  <view class="layout">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="statusBar" :style="{ height: getStatusBarHeight() + 'px' }"></view>
      <view class="titleBar" :style="{ height: getTitleBarHeight() + 'px' }">
        <view class="box">
          <image src="/static/logo.png" class="image"></image>
          <view class="name">清风聊天(190)</view>
          <view class="icon">
            <uni-icons type="pyq" size="30" class="se" @click="goMoment"></uni-icons>
            <uni-icons type="plusempty" size="30" @click="showPopover"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    <view class="fill" :style="{ height: getNavBarHeight() + 'px' }"></view>

    <!-- 弹窗组件 -->
    <view v-if="showPopoverContent" class="popover">
      <view class="item" @click="addFriend">
        <text>添加朋友</text>
      </view>
      <view class="item" @click="addGroup">
        <text>添加群聊</text>
      </view>
      <view class="item" @click="scanQRCode">
        <text>扫一扫</text>
      </view>
    </view>

    <!-- 聊天列表区域 -->
    <scroll-view
      class="chat-list"
      scroll-y
      :show-scrollbar="false"
      :style="{ height: `calc(100vh - ${getNavBarHeight() + 65}px)` }"
      @scrolltolower="loadMore"
    >
      <view
        class="chat-item"
        v-for="(item, index) in chatList"
        :key="item.id" 
        @click="chat(item)"
        @touchstart="handleTouchStart(index)"
        @touchend="handleTouchEnd(index)"
        @touchmove="handleTouchEnd(index)"
        :class="{ 'chat-item-active': activeIndex === index }"
      >
        <!-- 滑动删除组件 - 绑定 ref -->
        <uni-swipe-action ref="swipeActions"> 
          <uni-swipe-action-item
            :right-options="options"
            @click="handleSwipeClick(index)"
          >
            <view class="swipe-content">
              <!-- 头像 + 角标 -->
              <view class="chat-avatar-wrapper">
                <image
                  class="chat-avatar"
                  :src="item.avatar"
                ></image>
                <uni-badge
                  :text="item.unreadCount > 99 ? '99+' : (item.unreadCount > 0 ? item.unreadCount : '')"
                  v-if="item.unreadCount > 0"
                  type="error"
                  size="small"
                  class="badge-style"
                ></uni-badge>
              </view>
              <view class="chat-info">
                <view class="chat-top">
                  <!-- 名称容器改为弹性盒模型 -->
                  <view class="chat-name-wrap">
                    <text class="chat-name">{{ item.name }}</text>
                  </view>
                  <!-- 时间容器独立控制 -->
                  <view class="chat-time-wrap">
                    <text class="chat-time">{{ formatTime(item.time) }}</text>
                  </view>
                </view>
                <view class="chat-desc-container">
                  <text class="chat-desc" v-if="item.isGroupChat">
                    {{ item.desc }}
                    <text v-if="item.senderName && item.isGroupChat"> - {{ item.senderName }}</text>
                  </text>
                  <text class="chat-desc" v-else>
                    {{ item.desc }}
                  </text>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUpdated, getCurrentInstance } from 'vue';
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight } from '@/utils/system.js';

const showPopoverContent = ref(false);
const activeIndex = ref(-1);

const showPopover = () => showPopoverContent.value = true;
const hidePopover = () => showPopoverContent.value = false;

const addFriend = () => { 
  uni.navigateTo({
    url:"/pages/chat/AddFriend"
  })
  closeAll();
  hidePopover(); 
};

// 扫码功能实现
const scanQRCode = () => { 
  closeAll();
  hidePopover(); 
  startScan(); // 调用扫码函数
};

const options = ref([
  {
    text: '删除',
    style: {
      backgroundColor: '#dd524d', 
      color: '#fff',
      fontSize: '14px'
    }
  }
]);

// 为聊天数据添加唯一 ID
const chatList = ref([
  { id: 1, isGroupChat: true, avatar: '/static/logo.png', name: '生生的技术小屋alpha', senderName: 'fan', time: new Date(), desc: '我是说把架构师写名字上那位。', unreadCount: 3 },
  { id: 2, isGroupChat: true, avatar: '/static/logo.png', name: '景院二手闲置群1群', senderName: '东一', time: new Date(), desc: '[66条] 出季季红50代金券，44r出，四张…', unreadCount: 99 },
  { id: 3, isGroupChat: true, avatar: '/static/logo.png', name: '干大事儿人才交流吃喝玩乐群', senderName: '吃葡萄不吐葡萄皮儿', time: new Date(), desc: '[406条] 哈哈哈哈', unreadCount: 100 },
  { id: 4, isGroupChat: false, avatar: '/static/logo.png', name: '程序猿大本营', time: new Date(), desc: '我试过让它…', unreadCount: 0 },
  { id: 5, isGroupChat: true, avatar: '/static/logo.png', name: '球球分享CCC【禁言看公告】', senderName: '球球', time: new Date(), desc: '[253条] 奥妙内衣洗衣液内衣裤清洗液女…', unreadCount: 5 },
  { id: 6, isGroupChat: true, avatar: '/static/logo.png', name: '6.16打扫毕业生寝室志愿者招募群', senderName: 'CZ星宇', time: new Date(), desc: '[图片]', unreadCount: 8 },
  { id: 7, isGroupChat: true, avatar: '/static/logo.png', name: '湖北安全联盟', senderName: '1', time: new Date(), desc: '[269条] 快速注册公司 免费注册地址 全…', unreadCount: 20 },
  { id: 8, isGroupChat: true, avatar: '/static/logo.png', name: '朝夕软件库71群', senderName: '朝夕软件库', time: new Date(), desc: '[@所有人] 电视TV端听歌软件，比…', unreadCount: 50 },
  { id: 9, isGroupChat: false, avatar: '/static/logo.png', name: '公众号', time: new Date(), desc: '新余学院: 夏次见！送给2025届毕业生的歌！', unreadCount: 0 },
  { id: 10, isGroupChat: false, avatar: '/static/logo.png', name: '服务号', time: new Date(), desc: '[44条通知] [5条关注] 越秀地产悦秀会: 服务完成…', unreadCount: 7 }
]);

// 存储滑动组件引用
const swipeActions = ref([]);

// 时间格式化函数
const formatTime = (date) => {
  const hour = date.getHours().toString().padStart(2, '0');
  const minute = date.getMinutes().toString().padStart(2, '0');
  return `${hour}:${minute}`;
};

// 触摸开始，标记当前索引
const handleTouchStart = (index) => {
  activeIndex.value = index;
};

// 触摸结束，清空标记
const handleTouchEnd = (index) => {
  setTimeout(() => {
    activeIndex.value = -1;
  }, 150);
};

// 滑动删除事件：显示确认对话框，确认后关闭组件并删除
const handleSwipeClick = (index) => {
  // 先关闭当前滑动组件（防止确认过程中样式异常）
  if (swipeActions.value[index] && swipeActions.value[index].close) {
    swipeActions.value[index].close(); 
  }
  
  // 显示确认对话框
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条聊天记录吗？此操作不可撤销。',
    confirmText: '删除',
    confirmColor: '#dd524d',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        // 用户点击确认，执行删除
        chatList.value.splice(index, 1);
        uni.showToast({
          title: '删除成功',
          icon: 'none'
        });
      }
    }
  });
};

// 关闭所有滑动组件
const closeAll = () => {
  swipeActions.value.forEach((swipe, idx) => {
    if (swipe && swipe.close) {
      swipe.close();
    }
  });
};

//跳到聊天
const chat = (chat)=>{
  if(chat.isGroupChat)
  {
    uni.navigateTo({
      url:"/pages/chat/Group"
    })
    return;
  }
  uni.navigateTo({
    url:"/pages/chat/dialogue"
  })
}

// 滚动加载更多
const loadMore = () => {
  console.log('加载更多消息...');
  const unreadCount = Math.floor(Math.random() * 100); 
  const newData = {
    id: Date.now(), // 新增唯一 ID
    isGroupChat: Math.random() > 0.5,
    avatar: '/static/logo.png',
    name: `新测试${chatList.value.length + 1}`,
    senderName: Math.random() > 0.5 ? `测试用户${String.fromCharCode(65 + Math.floor(Math.random() * 26))}` : '',
    time: new Date(),
    desc: `这是新加载的测试消息${chatList.value.length + 1}`,
    unreadCount: unreadCount
  };
  chatList.value.push(newData);
};

// 更新滑动组件的 ref 引用
const updateSwipeRefs = () => {
  const instance = getCurrentInstance();
  if (instance && instance.$refs && instance.$refs.swipeActions) {
    swipeActions.value = instance.$refs.swipeActions; 
  }
};

// 组件挂载后初始化 ref
onMounted(() => {
  updateSwipeRefs();
});

// 组件更新后更新 ref
onUpdated(() => {
  updateSwipeRefs();
});

//跳到搜索界面
const goMoment = ()=>{
  uni.navigateTo({
    url:"/pages/chat/moment"
  })
}

//添加群聊
const addGroup = ()=>{
  uni.navigateTo({
    url:"/pages/chat/addGroup"
  })
}

// 扫码功能实现函数
const startScan = () => {
  uni.scanCode({
    onlyFromCamera: true,
    scanType: ['qrCode', 'barCode'],
    success: (res) => {
      const scanResult = res.result;
      handleScanResult(scanResult);
    },
    fail: (err) => {
      uni.showToast({
        title: '扫码失败，请重试',
        icon: 'none'
      });
      console.error('扫码失败:', err);
    }
  });
};

// 处理扫码结果
const handleScanResult = (result) => {
  uni.showModal({
    title: '扫码结果',
    content: `扫描到内容：${result}`,
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        if (result.startsWith('user:')) {
          const userId = result.split(':')[1];
          uni.navigateTo({
            url: `/pages/chat/AddFriend?userId=${userId}`
          });
        } else {
          uni.showToast({
            title: '暂不支持此类型的扫码内容',
            icon: 'none'
          });
        }
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.layout {
  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 100;
    background-color: #ffffff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);

    .titleBar {
      .box {
        display: flex;
        align-items: center;
        justify-content: space-around;
        width: 100%;
        height: 100%;
        max-height: 60px;
        padding: 0 15px;
        .image {
          margin-left: -30px;
          width: 60rpx;
          height: 60rpx;
        }
        .icon {
          display: flex;
          align-items: center;
          .se {
            margin-right: 10px;
          }
        }
      }
    }
  }
}

.fill {
  height: 100px;
}

.popover {
  position: fixed;
  top: 60px;
  right: 10px;
  background-color: black;
  z-index: 1000;
  border-radius: 5px;
  overflow: hidden;
  .item {
    padding: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    &:hover {
      background-color: #555;
    }
  }
}

/* 聊天列表样式 */
.chat-list {
  padding: 10px;
  background-color: #f0f0f0;
  /* 隐藏滚动条 */
  ::-webkit-scrollbar {
    display: none !important;
  }
  scrollbar-width: none !important;
  -ms-overflow-style: none !important;
}

.chat-item {
  margin-bottom: 15px;
  overflow: hidden;
  transition: background-color 0.15s ease;
}

.chat-item-active {
  background-color: #e8e8e8;
}

/* 滑动内容样式 */
.swipe-content {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e5e5;
}

/* 头像 + 角标容器 */
.chat-avatar-wrapper {
  position: relative;
  width: 80rpx;
  height: 80rpx;
  margin-right: 10px;
}

.chat-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
}

/* 定义角标样式 */
.badge-style {
  position: absolute;
  display: flex;
  top: -4rpx;
  right: -10rpx;
}

.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-right: 10rpx;
}

/* 顶部信息栏优化 */
.chat-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

/* 名称容器优化 */
.chat-name-wrap {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0;
}

.chat-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 时间容器独立优化 */
.chat-time-wrap {
  width: 120rpx;
  display: flex;
  justify-content: flex-end;
  margin-left: 10rpx;
}

.chat-time {
  font-size: 26rpx;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 15px;
}

/* 描述信息样式 */
.chat-desc-container {
  font-size: 28rpx;
  color: #666;
  line-height: 40rpx;
  padding-right: 10rpx;
}

.chat-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 40rpx;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>